package com.crm.service.impl;

import com.crm.base.BaseServiceImpl;
import com.crm.domain.entity.Module;
import com.crm.domain.entity.Permissions;
import com.crm.domain.entity.Role;
import com.crm.domain.entity.User;
import com.crm.mapper.RoleMapper;
import com.crm.service.ModuleService;
import com.crm.service.PermissionsService;
import com.crm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.stream.Collectors;

/**
 * 角色业务层实现类
 */

@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private PermissionsService permissionsService;
    @Autowired
    private ModuleService moduleService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addPermission(Integer roleId, Integer[] moduleIds, HttpSession session) {
        if (roleId != null) {
            // 根据角色ID删除该角色的权限
            permissionsService.deletePermissionByRoleId(roleId);
        }

        if (moduleIds.length > 0) {
            // 添加用户权限
            permissionsService.addPermission(new Permissions(null, roleId, moduleIds));
        }

        // 更新当前登录用户权限
        User user = (User) session.getAttribute("session_user");
        user.setPerms(moduleService.findModuleByUid(user.getId(), "").stream().map(Module::getModuleUrl).collect(Collectors.toList()));

        return true;
    }
}
